﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Nutrapp.DBAL;
using System.IO;
using Nutrapp.Models;
using System.Diagnostics;

namespace Nutrapp.Controllers
{
    //[Authorize]

    public class RecipeController : Controller
    {
        //
        // GET: /Recipe/
        private IRecipeRepository repository;
        public int PageSize = 6; //how many items per page
        private NutrappDataContext context = new NutrappDataContext();

        public RecipeController(IRecipeRepository recipeRepository)
        {
            repository = recipeRepository;
        }


        public ViewResult Index(int page = 1)
        {
            RecipeListViewModel model = new RecipeListViewModel
            {
                recipes = repository.Recipes.OrderBy(r => r.Name).Skip((page - 1) * PageSize).Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = repository.Recipes.Count()
                }
            };
            return View(model);
        }

        public ViewResult View(int id)
        {
            Recipe recipe;
            RecipeModel rec = new RecipeModel(); ;
            if (id > 0)
            {
                recipe = repository.Recipes.FirstOrDefault(r => r.ID == id);

                if (recipe != null)
                {
                    rec.ID = id;
                    rec.Name = recipe.Name;
                    rec.Cost = recipe.Cost;
                    rec.Picture = recipe.Picture;
                    rec.Instruction = recipe.Instruction;
                    rec.IngredientLines = recipe.Recipe_Ingredients.ToList();
                    rec.Rating = recipe.Rating;
                    rec.Protein = recipe.Protein.Value;
                    rec.Fat = recipe.Fat.Value;
                    rec.Calories = recipe.Calories.Value;
                    rec.Carbohydrate = recipe.Carbohydrate.Value;
                }
            }

            //RecipeModel recipe = (id > 0) ? repository.GetRecipe(id) : new RecipeModel();

            return View(rec);
        }

        public ActionResult Create()
        {
            return View("Edit", new RecipeModel());
        }

        public ViewResult Edit(int id)
        {
            Recipe recipe;
            RecipeModel rec = new RecipeModel(); ;
            if (id > 0)
            {
                recipe = repository.Recipes.FirstOrDefault(r => r.ID == id);

                if (recipe != null)
                {
                    rec.ID = id;
                    rec.Name = recipe.Name;
                    rec.Cost = recipe.Cost;
                    rec.Picture = recipe.Picture;
                    rec.Instruction = recipe.Instruction;
                    rec.IngredientLines = recipe.Recipe_Ingredients.ToList();
                    rec.Rating = recipe.Rating;
                    rec.Protein = recipe.Protein.Value;
                    rec.Fat = recipe.Fat.Value;
                    rec.Calories = recipe.Calories.Value;
                    rec.Carbohydrate = recipe.Carbohydrate.Value;
                }
            }

            //RecipeModel recipe = (id > 0) ? repository.GetRecipe(id) : new RecipeModel();

            return View(rec);
        }

        [HttpPost]
        public ActionResult Edit(RecipeModel recipe, int[] ingr, int[] quant, int[] unit, HttpPostedFileBase image)
        {
            // if (ModelState.IsValid)
            //{
            if (((recipe.ID == 0 && IsImage(image)) || (recipe.ID > 0)) && (IsCorrectlyPopulated(ingr)))
            {
                recipe.IngredientLines = new List<Recipe_Ingredient>();

                for (int i = 0; i < ingr.Length; i++)
                {
                    var c = new Recipe_Ingredient { IID = ingr[i], UID = unit[i], Quantity = quant[i] };

                    recipe.IngredientLines.Add(c);
                }

                if ((image != null && image.ContentLength > 0) && IsImage(image))
                {
                    var pic = System.IO.Path.GetFileName(recipe.ID + "-" + image.FileName);
                    String serverPath = Server.MapPath("~/Upload/RecipeImage");
                    var path = Path.Combine(serverPath, pic);

                    image.SaveAs(path);

                    recipe.Picture = pic;
                }

                
                repository.SaveRecipe(recipe);
                TempData["message"] = string.Format("{0} has been saved", recipe.Name);

                return RedirectToAction("Index");
            }
            else
            {
                TempData["message"] = string.Format("{0} has not been saved - wrong information", recipe.Name);

                return View(recipe.ID);
            }
            //}
            //else
            //{
            //    return View(recipe);
            //}

        }


        [HttpPost]
        public ActionResult Delete(int id)
        {
            //handle exception for id
            Recipe deletedRecipe = repository.Recipes.FirstOrDefault(r => r.ID == id);
            if (deletedRecipe != null)
            {
                int deletedRecipeId = repository.DeleteRecipe(id);
                if (deletedRecipeId != 0)
                {
                    TempData["message"] = string.Format("{0} was deleted", deletedRecipe.Name);
                }

            }
            return RedirectToAction("Index");
        }

        private bool IsImage(HttpPostedFileBase file)
        {
            if (file == null)
            {
                return false;
            }

            if (file.ContentType.Contains("image"))
            {
                return true;
            }

            string[] formats = new string[] { ".jpg", ".png", ".gif", ".jpeg" };

            return formats.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase));
        }

        private bool IsCorrectlyPopulated(int[] list)
        {
            var l = list.ToList();

            return ((l.Where(x => x > 0).ToList().Count == l.Count) && (l.Count > 0) && (!l.GroupBy(n => n).Any(c => c.Count() > 1)));
        }

        
    }
}
